package com.dxy.df.core.shiro;

import com.alibaba.fastjson.JSONObject;
import com.dxy.df.constants.ConstNumbers;
import com.dxy.df.constants.ConstStrings;
import com.dxy.df.constants.ErrorEnum;
import com.dxy.df.core.model.Rs;
import org.apache.http.HttpStatus;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Objects;
import java.util.UUID;

/**
 * oauth2过滤器
 *
 * @date 2017-05-20 13:00
 */
public class LoginFilter extends AuthenticatingFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        return new LoginToken(UUID.randomUUID() + "");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Principal t = httpServletRequest.getUserPrincipal();
        String url = httpServletRequest.getRequestURI();
        String loginUrl = "/api/users/login";
        System.out.println("---------请求进来了------------");

        if (Objects.equals("local", System.getProperty(ConstStrings.SPRING_PROFILES_ACTIVE))) {
            String testDebugDxyUserName = httpServletRequest.getHeader(ConstStrings.TEST_DEBUG_DXYUSERNAME);
            if (null != testDebugDxyUserName && !StringUtils.isEmpty(testDebugDxyUserName)) {
                return true;
            }
        }

        if (null != t) {
            Subject currentUser = SecurityUtils.getSubject();
            if (currentUser.isAuthenticated()) {
                currentUser.getSession().setTimeout(ConstNumbers.SERVER_SESSION_TIMEOUT);
            }
            return true;

        } else if (url.equals(loginUrl)) {
            boolean loginFlag = executeLogin(request, response);
            return loginFlag;
        } else {
            redirectToLogin(request, response);
            return false;
        }

    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {
            httpResponse.setContentType("application/json;charset=utf-8");
            Rs r = Rs.error(ErrorEnum.LOGIN_ERROR.getCode(), ErrorEnum.LOGIN_ERROR.getMsg());
            httpResponse.getWriter().print(JSONObject.toJSONString(r));
        } catch (IOException ee) {
            LOGGER.error(ee.getMessage());
        }
        return false;
    }

}
